package ui.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.linchaolong.android.imagepicker.ImagePicker;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.DoTheWorkSelectAdapter;
import adapter.GridImageAdapter;
import adapter.ImageAdapter;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.ListOfPapersBean;
import bean.QuestionAnswerDetailBean;
import bean.QuestionBean;
import jp.wasabeef.richeditor.RichEditor;
import student.andlei.com.student.R;
import utils.GsonUtils;
import utils.StringUtils;
import view.BottomAnswerPopWindow;
import view.ConfirmPopWindow;

/**
 * 查看题目
 */
public class LookSubmittedActivity extends BaseNetActivity{
    private int maxSelectNum = 3;
    private int i = 0;
    private TextView tv_numbr,
            tv_time,
            tv_answersheet,
            tv_scrappaper;
    private TextView tv_typename;
    private RichEditor tv_content;

    private CheckBox check_shoucang;
//    private ImageView check_pen,
//            check_rubber;
    private List<ListOfPapersBean.mList.Questions.Options> optionsList = new ArrayList<>();
    private DoTheWorkSelectAdapter selectAdapter;
    private RecyclerView recy_xuanze;
    private LinearLayout
            layout_wacom;
    //private List<String> list;
    private ImagePicker imagePicker;
    private RecyclerView gv;
    private ImageAdapter adapter;
    private ImageView img_left,
            img_right;
    private ScrollView scrollView;
    private RichEditor ed_content;
    private ImageView img_photo,img_camera,img_update;
//    private LinePathView paletteView;
//    private ImageView img_wacom;
    private List<ListOfPapersBean.mList.Questions> mLists = new ArrayList<>();
    private View layoutview;
    private int paper_id;//试卷id
    private int paper_question_id;//题目id
    private int student_task_id; // 学生作业id
    private int answer_id;//答题卡id
    private int check_type;//1:收藏（默认） 2:取消收藏
    private Button bt_lookanswer;//查看答案
    private String drawing_board_image = "";//手写板图片
    private String answer_image;//上传图片
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseBack(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }

    @Override
    public void success(String action, BaseBean baseBean) {
        hideLoadDialog();
        if (baseBean.code == 200) {
            if (action.equals("Task/getAllQuestion")) {
                ListOfPapersBean bean = (ListOfPapersBean) GsonUtils.getInstance(this).parseComplexJArrayByCommon(baseBean, ListOfPapersBean.class);
                answer_id = bean.answer_id;
                if(bean.paper_type == 3){
                    check_shoucang.setVisibility(View.GONE);
                }
                if (bean.list == null) {
                    return;
                }
                mLists.clear();
                for (int i = 0; i < bean.list.size(); i++) {
                    //bean.list.get(i).type_name
                    for (int j = 0; j < bean.list.get(i).questions.size(); j++) {
                        bean.list.get(i).questions.get(j).type_id = bean.list.get(i).type_id;
                        bean.list.get(i).questions.get(j).type_name = bean.list.get(i).type_name;
                    }

                    mLists.addAll(bean.list.get(i).questions);
                }
                for (int h = 0; h < mLists.size(); h++) {
                    for (int n = 0; n < mLists.get(h).options.size(); n++) {
                        if (!StringUtils.isNull(mLists.get(h).answer)) {
                            if (mLists.get(h).answer.equals(mLists.get(h).options.get(n).idx)) {
                                mLists.get(h).options.get(n).isSelect = 1;
                            } else {
                                mLists.get(h).options.get(n).isSelect = 0;
                            }
                        }
                    }
                }
                updateUi(i);
            } else if (action.equals("Task/getQuestion")) {
                QuestionAnswerDetailBean bean  = (QuestionAnswerDetailBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,QuestionAnswerDetailBean.class);
                String slore ="";
                //0未公布答案 1已公布答案
                if(bean.answer_status == 0){
                    toast("老师暂未公布答案，请稍后再试");
                    return;
                }
                if(bean == null){return;}
                for(QuestionBean.Lore lore : bean.lore){
                    slore+=lore.lore_content+",";
                }
                new BottomAnswerPopWindow(this, ""+bean.answer.answer, ""+bean.question.answer, ""+bean.question.analysis, ""+slore).showAtBottom(layoutview);
            } else if (action.equals("Task/collectQuestion")) {
                if (check_type == 1) {
                    mLists.get(i).is_favorite = 1;
                    check_shoucang.setChecked(true);
                    check_shoucang.setText("  已收藏");
                } else {
                    mLists.get(i).is_favorite = 0;
                    check_shoucang.setChecked(false);
                    check_shoucang.setText("  未收藏");
                }
            } else if (action.equals("Task/saveAnswer")) {
                selectList.clear();
                adapter.notifyDataSetChanged();
                PictureFileUtils.deleteCacheDirFile(LookSubmittedActivity.this);
            }
        } else {
            if (action.equals("Task/collectQuestion")) {
                if (check_shoucang.isChecked()) {
                    check_shoucang.setChecked(false);
                } else {
                    check_shoucang.setChecked(true);
                }
//                if(check_type==1){
//                    mLists.get(i).is_favorite = 1;
//                    check_shoucang.setChecked(true);
//                    check_shoucang.setText("  已收藏");
//                }else {
//                    mLists.get(i).is_favorite = 0;
//                    check_shoucang.setChecked(false);
//                    check_shoucang.setText("  未收藏");
//                }
            }
            toast(baseBean.getMsg());
        }
    }

    @Override
    public void error(String action, Throwable e) {
        hideLoadDialog();
    }

    @Override
    protected int getLayoutId() {
        layoutview = View.inflate(context, R.layout.activity_dothework, null);
        return R.layout.activity_dothework;
    }

    @Override
    protected void findViews() {
        tv_numbr = getView(R.id.tv_number);
        tv_time = getView(R.id.tv_time);
        tv_time.setVisibility(View.GONE);
        bt_lookanswer = getView(R.id.bt_lookanswer);
        check_shoucang = getView(R.id.check_shoucang_);
        tv_answersheet = getView(R.id.tv_answersheet);
        tv_scrappaper = getView(R.id.tv_Scrappaper);
        tv_typename = getView(R.id.tv_answertype);
        tv_content = getView(R.id.tv_content);
        tv_content.setInputEnabled(false);
        tv_content.setInitialScale(300);
//        check_pen = getView(R.id.check_pen);
//        check_rubber = getView(R.id.check_rubber);
        recy_xuanze = getView(R.id.rycl_xuanze);
        recy_xuanze.setEnabled(false);
//        img_wacom = getView(R.id.img_wacom);
//        img_wacom.setVisibility(View.VISIBLE);

        layout_wacom = getView(R.id.layout_wacom);
//        layout_pen = getView(R.id.layout_pen);
//        layout_rubber = getView(R.id.layout_rubber);
//        img_clean = getView(R.id.img_clean);
        scrollView = getView(R.id.scrollView);
//        paletteView = getView(R.id.plt_wacom);
//        paletteView.setVisibility(View.GONE);
        img_left = getView(R.id.img_left);
        img_right = getView(R.id.img_right);
        gv = getView(R.id.grid_view);
    }

//    private void initImagePicker() {
//        GridLayoutManager manager = new GridLayoutManager(context, 6, GridLayoutManager.VERTICAL, false);
//        gv.setLayoutManager(manager);
//        adapter = new ImageAdapter(context, R.layout.item_img,selectList);
//        gv.setAdapter(adapter);
//
//        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                LocalMedia media = selectList.get(position);
//                String pictureType = media.getPictureType();
//                int mediaType = PictureMimeType.pictureToVideo(pictureType);
//                switch (mediaType) {
//                    case 1:
//                        // 预览图片
//                        PictureSelector.create(LookSubmittedActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
//                        break;
//                }
//            }
//        });
//    }

    @Override
    protected void formatViews() {
        //输入答案
        ed_content = getView(R.id.ed_content);
        bt_lookanswer.setOnClickListener(this);
        bt_lookanswer.setVisibility(View.VISIBLE);
        //选择图片 手写板
        check_shoucang = getView(R.id.check_shoucang_);
        tv_answersheet = getView(R.id.tv_answersheet);
        tv_scrappaper = getView(R.id.tv_Scrappaper);
        ed_content.setInputEnabled(false);
        tv_answersheet.setOnClickListener(this);
        tv_scrappaper.setOnClickListener(this);
//        img_clean.setOnClickListener(this);
        img_left.setOnClickListener(this);
        img_right.setOnClickListener(this);
//        check_pen.setOnClickListener(this);
//        check_rubber.setOnClickListener(this);
        check_shoucang.setOnClickListener(this);

//        layout_pen.setBackgroundResource(R.color.check_color);
//        initImagePicker();
        ed_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    //mLists.get(i).shouxieimg = paletteView.getBitMap();
//                    if (mLists.size() > 0) {
//                        String mpath = "/sdcard/dskqxt/pic/" + mLists.get(i).paper_question_id + ".jpg";
//                        //String mpath = App.getAppCacheDir(DoTheWorkActivity.this) + mLists.get(i).paper_question_id + ".jpg";
//                        //"/sdcard/dskqxt/pic/"
//                        try {
//                            paletteView.save(mpath, paletteView.getBitMap());
//                            mLists.get(i).shouxieimg = mpath;
//                            LogUtil.app("----->手写板对象已赋值");
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
                    //允许ScrollView截断点击事件，ScrollView可滑动
                    scrollView.requestDisallowInterceptTouchEvent(false);
                } else {
                    //不允许ScrollView截断点击事件，点击事件由子View处理
                    scrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });
    }

    @Override
    protected void formatData() {
//        for(int i = 0;i<10;i++){
//            ListOfPapersBean.mList bean = new ListOfPapersBean.mList();
//            bean.questions = new ListOfPapersBean.mList.Questions();
//            bean.questions.paper_question_id = i;
//            mLists.add(bean);
//        }
//        for(int i = 0;i<4;i++){
//            ListOfPapersBean.mList.Questions.Options options = new ListOfPapersBean.mList.Questions.Options();
//            optionsList.add(options);
//        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recy_xuanze.setLayoutManager(layoutManager);
        selectAdapter = new DoTheWorkSelectAdapter(R.layout.item_work_select, optionsList);
        recy_xuanze.setAdapter(selectAdapter);
//        selectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                for (int i = 0; i < optionsList.size(); i++) {
//                    if (position == i) {
//                        optionsList.get(i).setIsSelect(1);
//                        //optionsList.get(i).isSelect = 1;
//                    } else {
//                        optionsList.get(i).setIsSelect(0);
//                        //optionsList.get(i).isSelect = 0;
//                    }
//                }
//                adapter.notifyDataSetChanged();
//            }
//        });
        tv_numbr.setText((i + 1) + "/" + mLists.size() + "题");
        loadDataList();
    }
    private void loadDataList() {
        Map<String, String> map = new HashMap<>();
        map.put("student_task_id", "" + student_task_id);
        post("Task/getAllQuestion", map, BaseBean.class, false);

    }

    private void checkTogglet() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "" + check_type);
        map.put("question_id", "" + mLists.get(i).question_id);
        post("Task/collectQuestion", map, BaseBean.class, true);
    }
    @Override
    protected void getBundle(Bundle bundle) {
//        paper_id = bundle.getInt("paper_id");
        student_task_id = bundle.getInt("student_task_id");
        i = bundle.getInt("order");
        setTitle("查看题目");
    }



    @SuppressLint("Range")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //查看答案
            case R.id.bt_lookanswer:
                Map<String,Object> map = new HashMap<>();
                map.put("paper_question_id",mLists.get(i).paper_question_id);
                map.put("answer_id",answer_id);
                post("Task/getQuestion",map,BaseBean.class,false);
                break;
            //向左按钮
            case R.id.img_left:
                if (i <= 0) {
                    //toast("已是第一题");
                    return;
                }
                i--;
//                paletteView.clear();
                updateUi(i);
                break;
            //向右按钮
            case R.id.img_right:
                if (i >= mLists.size() - 1) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("student_task_id", student_task_id);
                    bundle.putInt("answer_id", answer_id);
                    jumpTo(AnswerSheetActivity.class, 0,bundle);
                    //toast("已是最后一题");
                    return;
                }
                i++;
//                paletteView.clear();
                updateUi(i);
                break;
            //画笔
            case R.id.check_pen:
                //toast("画笔");
//                paletteView.setPenColor(Color.BLACK);
//                paletteView.setPaintWidth(5);
//                // paletteView.setMode(PaletteView.Mode.DRAW);
//                layout_pen.setBackgroundResource(R.color.check_color);
//                layout_rubber.setBackgroundResource(R.color.uncheck_color);
                break;
            //橡皮
            case R.id.check_rubber:
                //toast("橡皮");
//                paletteView.setPenColor(Color.WHITE);
//                paletteView.setPaintWidth(50);
//                // paletteView.setMode(PaletteView.Mode.ERASER);
//                layout_rubber.setBackgroundResource(R.color.check_color);
//                layout_pen.setBackgroundResource(R.color.uncheck_color);
                break;
            //清除手写板按钮
            case R.id.img_clean:
                //toast("清除手写板按钮");
//                paletteView.clear();
//                String mpath = "/sdcard/dskqxt/pic/" + mLists.get(i).paper_question_id + ".jpg";
//                try {
//                    paletteView.save(mpath, paletteView.getBitMap());
//                    mLists.get(i).shouxieimg = "";
//                    LogUtil.app("----->手写板对象已赋值");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                break;
            //草稿本
            case R.id.tv_Scrappaper:
                new ConfirmPopWindow(this).showAtBottom(layoutview);
                break;
            //答题卡
            case R.id.tv_answersheet:
                Bundle bundle = new Bundle();
                bundle.putInt("student_task_id", student_task_id);
                bundle.putInt("answer_id", answer_id);
                jumpTo(AnswerSheetActivity.class,0, bundle);
                break;
            //收藏按钮
            case R.id.check_shoucang_:
                //1:收藏（默认） 2:取消收藏
                if (check_shoucang.isChecked()) {
                    check_type = 1;
                } else {
                    check_type = 2;

                }
                checkTogglet();
                break;

        }
    }
    private void updateUi(int i) {
        tv_numbr.setText((i + 1) + "/" + mLists.size() + "题");
        tv_typename.setText("(" + mLists.get(i).type_name + ")");
        //RichText.fromHtml(mLists.get(i).question_content).into(tv_content);
        tv_content.setHtml(mLists.get(i).question_content);
        //tv_content.setText(mLists.get(i).question_content);
        optionsList = mLists.get(i).options;
        selectAdapter.setNewData(optionsList);
        if (mLists.get(i).is_favorite == 0) {
            check_shoucang.setChecked(false);
            check_shoucang.setText("  未收藏");
        } else {
            check_shoucang.setChecked(true);
            check_shoucang.setText("  已收藏");
        }
        Log.i("imglist--->", "" + mLists.get(i).imglist);
        ed_content.setHtml(mLists.get(i).answer_image);
//        if (mLists.get(i).imglist != null && mLists.get(i).imglist.size() > 0) {
//            adapter.setNewData(mLists.get(i).imglist);
//            adapter.notifyDataSetChanged();
//        } else {
//            List<LocalMedia> mediaList = new ArrayList<>();
//            adapter.setNewData(mediaList);
//            adapter.notifyDataSetChanged();
//        }
//        if (!StringUtils.isNull(mLists.get(i).shouxieimg)) {
//            if (mLists.get(i).shouxieimg.contains("http")) {
//
//                Log.i("shouxieimg", i + "-----" + mLists.get(i).shouxieimg);
//                loadImageSimpleTarget(mLists.get(i).shouxieimg);
//            } else {
//                Bitmap bmp = BitmapFactory.decodeFile(mLists.get(i).shouxieimg);//filePath
//                Drawable drawable = new BitmapDrawable(bmp);
////                paletteView.setBackground(drawable);
//            }
//        }
        //1.单选题，2.多选题，3.判断题，4.填空题，5.解答题，6.实验题，7.作文题
        switch (mLists.get(i).type_id) {
            case 1:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 2:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 3:
                layout_wacom.setVisibility(View.GONE);
                break;
            case 4:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            case 5:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            case 6:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            case 7:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
            default:
                layout_wacom.setVisibility(View.VISIBLE);
                break;
        }
    }

    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 不需要的api可以不写
//            PictureSelector.create(LookSubmittedActivity.this)
//                    .openGallery(PictureMimeType.ofImage())
//                    .theme(R.style.picture_default_style)
//                    .maxSelectNum(maxSelectNum)
//                    .minSelectNum(1)
//                    .selectionMode(PictureConfig.MULTIPLE)
//                    .previewImage(true)
//                    .isCamera(true)
//                    .enableCrop(false)
//                    .compress(true)
//                    .glideOverride(160, 160)
//                    .previewEggs(true)
//                    .withAspectRatio(1, 1)
//                    .hideBottomControls(false)
//                    .isGif(true)
//                    .freeStyleCropEnabled(false)
//                    .circleDimmedLayer(false)
//                    .showCropFrame(false)
//                    .showCropGrid(false)
//                    .openClickSound(false)
//                    .selectionMedia(selectList)
//                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    };
//    private void loadImageSimpleTarget(String str) {
//        Glide.with(context).asBitmap().load(str).into(new SimpleTarget<Bitmap>() {
//            @Override
//            public void onResourceReady(final Bitmap resource, Transition<? super Bitmap> transition) {
//                Drawable drawable = new BitmapDrawable(resource);
//                Log.i("shouxieimg", i + "-----" + resource+"----"+paletteView);
//                //setBackgroundDrawable
//                //paletteView.setBackgroundDrawable(drawable);
//                paletteView.setBackground(drawable);
//            }
//        });
//    }
}
